package cn.office.controller;

import cn.office.enums.file.FileContentTypeEnums;
import cn.office.param.PdfGenerateParam;
import cn.office.param.UserInfo;
import cn.office.utils.PdfUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.velocity.VelocityContext;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.*;

@RestController
@Slf4j
@RequestMapping("/pdf")
public class PdfController {

    @RequestMapping(value = "/generatePdf", method = RequestMethod.GET)
    public void generatePdf(HttpServletResponse response) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ByteArrayInputStream byteArrayInputStream = null;
        OutputStream outputStream = null;
        try {
            PdfGenerateParam pdfGenerateParam = new PdfGenerateParam();
            pdfGenerateParam.setTemplateName("userList.vm");
            Map<String, Object> map = mergeData();
            pdfGenerateParam.setVelocityContext(new VelocityContext(map));
            PdfUtils.createPdf(pdfGenerateParam, byteArrayOutputStream);
            byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
            //避免空行
            response.reset();
            // 设置文件类型
            response.setContentType(FileContentTypeEnums.pdfTypeEnum.PDF.getContentType());
            //response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("用户列表", "UTF-8") + ".pdf");
            response.setHeader("Content-disposition", "inline;filename=" + URLEncoder.encode("用户列表", "UTF-8") + ".pdf");
            outputStream = response.getOutputStream();
            byte[] b = new byte[1024];
            int len;
            while ((len = byteArrayInputStream.read(b)) > 0) {
                outputStream.write(b, 0, len);
            }
        } catch (Exception e) {
            log.error("创建PDF异常：\n{}", e);
        } finally {
            if (byteArrayOutputStream != null) {
                try {
                    byteArrayInputStream.close();
                } catch (IOException e) {
                    log.error("关闭输出流异常：\n{}", e);
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    log.error("关闭输出流异常：\n{}", e);
                }
            }
            if (byteArrayInputStream != null) {
                try {
                    byteArrayInputStream.close();
                } catch (IOException e) {
                    log.error("关闭输入流异常：\n{}", e);
                }
            }
        }
    }

    Map<String, Object> mergeData() {
        Map<String, Object> map = new HashMap<>();
        List<UserInfo> userInfoList = new ArrayList<>();
        userInfoList.add(new UserInfo("张三", 22, "男", new Date(), "北京", "1995-12-12"));
        userInfoList.add(new UserInfo("李四", 26, "男", new Date(), null, "1999-12-12"));
        userInfoList.add(new UserInfo(null, 60, null, new Date(), "广州", null));
        userInfoList.add(new UserInfo("赵六", 22, "男", new Date(), null, "1994-12-12"));
        map.put("userInfoList", userInfoList);
        map.put("total", userInfoList.size());
        map.put("avgAge", (int) userInfoList.stream().mapToInt(UserInfo::getAge).average().getAsDouble());

        return map;
    }


}
